<template>
	<view class="user" :class="[isDark?'dark':'', AppStyle]" :style="{'background-color':isDark?'#1c1c1c':'#f6f6f6','min-height':isDark?'100vh':'auto'}">
		<view class="header" :style="[{height:CustomBar + 'px'}]" :class="AppStyle">
			<view class="cu-bar" :style="{'height': CustomBar + 'px','padding-top':StatusBar + 'px', 'background-color':isDark?'#1c1c1c':'#ffffff'}">
				<view class="action" @tap="back">
					<text class="cuIcon-back" :style="{'color':isDark?'#ffffff':'#000000'}"></text>
				</view>
				<view class="content text-bold" :style="[{top:StatusBar + 'px'}, {'color':isDark?'#ffffff':'#000000'}]">
					{{$t('user.rebate.invitefriend')}}
				</view>
				<view class="action">
					<text class="text-blue" @tap="toLink('/pages/user/inviteList')">{{$t('user.rebate.inviterecord')}}</text>
				</view>
			</view>
		</view>
		<view :style="[{padding:NavBar + 'px 10px 0px 10px'}]"></view>
		<view class="data-box" :style="{'background-color':isDark?'#1c1c1c':'#ffffff'}">
			<view class="menu margin-top" :style="{'background-color':isDark?'#1c1c1c':'#ffffff'}">
				<!--  #ifdef APP-PLUS -->
				<block v-if="adsVideoType==0 || adsVideoType==1">
					<view class="menu-item" v-if="adpid!=''&&adpid" :style="{'background-color':isDark?'#1c1c1c':'#ffffff', 'border-bottom':isDark?'1px solid #2c2c2c':'1px solid #e5e5e5'}">
						<view class="content">
							<text class="text-lg" :style="{'color':isDark?'#ffffff':'#000000'}">{{$t('user.rebate.adsearnreward')}}</text>
							<text class="text-gray text-sm" :style="{'color':isDark?'#888888':'#999999'}">{{$t('user.rebate.randomobtain') + currencyName}}</text>
						</view>
						<view class="action">
							<text class="cu-btn round bg-gradual-orange" @tap="show">
								<text class="cuIcon-videofill margin-right-xs"></text>{{$t('user.rebate.obtain')}}
							</text>
						</view>
					</view>
				</block>
				<!--  #endif -->
			</view>
		</view>
		<view class="data-box" :style="{'background-color':isDark?'#1c1c1c':'#ffffff'}">
			<block v-if="islock==false">
				<view class="invite margin" :style="{'background-color':isDark?'#1c1c1c':'#ffffff'}">
					<view class="invite-title text-xl padding-bottom" :style="{'color':isDark?'#ffffff':'#000000'}">
						{{$t('user.rebate.goodfriend') + currencyName}}
						<view class="text-sm tn-margin-sm" :style="{'color':isDark?'#888888':'#999999'}">{{$t('user.rebate.friendregcode')}}</view>
					</view>
					<view class="invite-main padding-tb-xl">
						<view class="invite-text text-center">
							<text class="text-price text-xxl text-bold text-blue">{{invitationCode}}</text>
						</view>
					</view>
					<view class="invite-btn flex justify-center padding-bottom">
						<text class="cu-btn round bg-gradual-blue" @tap="copy(invitationCode)">
							<text class="cuIcon-copy margin-right-xs"></text>{{$t('user.rebate.copyinvitecode')}}
						</text>
					</view>
				</view>
				
				<view class="padding-lr" :style="{'background-color':isDark?'#1c1c1c':'#ffffff'}">
					<view class="text-content" v-html="yqtext" :style="{'color':isDark?'#ffffff':'#000000'}"></view>
				</view>
			</block>
			
			<block v-if="islock==true">
				<view class="invite margin text-center padding-xl" :style="{'background-color':isDark?'#1c1c1c':'#ffffff'}">
					<text :style="{'color':isDark?'#888888':'#999999'}">{{$t('user.rebate.invitefunclose')}}</text>
				</view>
			</block>
		</view>
		<!--加载遮罩-->
		<view class="loading" v-if="isLoading==0">
			<view class="loading-main">
				<image src="../../static/loading.gif"></image>
			</view>
		</view>
		<!--加载遮罩结束-->
	</view>

</template>

<script>
	const ERROR_CODE = [-5001, -5002, -5003, -5004, -5005, -5006];
	import waves from '@/components/xxley-waves/waves.vue';
	import {
		localStorage
	} from '../../js_sdk/mp-storage/mp-storage/index.js'
	import darkModeMixin from '@/utils/darkModeMixin.js'
	export default {
		mixins: [darkModeMixin],
		data() {
			return {
				StatusBar: this.StatusBar,
				CustomBar: this.CustomBar,
				NavBar: this.StatusBar + this.CustomBar,
				AppStyle: this.$store.state.AppStyle,


				userInfo: null,
				token: "",

				isLoading: 0,

				modalName: null,

				currencyName: "",
				invitationCode: "--",
				codeImg: null,
				islock: false,
				yqtext: "",
				title: $t('user.rebate.seevideoadvert'),
				loading: false,
				loadError: false,
				adpid: '',
				adsLogid: '',
				//服务端回调相关配置
				urlCallback: {
					userId: '0',
					extra: 'RuleApp'
				},
				adsVideoType: 1,

			}
		},
		onPullDownRefresh() {
			var that = this;
			if (localStorage.getItem('token')) {

				that.token = localStorage.getItem('token');
			}
			var timer = setTimeout(function() {
				uni.stopPullDownRefresh();
			}, 1000)
		},
		onReady() {
			// #ifdef APP-PLUS
			this.adsVideoType = this.$API.GetAdsVideoType();
			this.adpid = this.$API.GetAdpid();
			if (this.adpid != "" && this.adpid) {
				this.adOption = {
					adpid: this.adpid
				};
				this.createAd();
			}
			// #endif
		},
		onShow() {
			var that = this;
			// #ifdef APP-PLUS
			//plus.navigator.setStatusBarStyle("dark")
			// #endif
			if (localStorage.getItem('userinfo')) {
				that.userInfo = JSON.parse(localStorage.getItem('userinfo'));
				that.userInfo.style = "background-image:url(" + that.userInfo.avatar + ");"
				that.urlCallback.userId = that.userInfo.uid;
			}
			if (localStorage.getItem('token')) {
				that.token = localStorage.getItem('token');
				that.getInvitationCode();
			}
		},
		onLoad() {
			var that = this;
			// #ifdef APP-PLUS || MP
			that.NavBar = that.CustomBar;
			// #endif
			if (localStorage.getItem('userinfo')) {
				that.userInfo = JSON.parse(localStorage.getItem('userinfo'));
				that.urlCallback.userId = that.userInfo.uid;
			}
		},
		mounted() {
			this.getset();
		},
		methods: {
			getset() {
				var that = this;
				uni.request({
					url: that.$API.SPset(),
					method: 'GET',
					dataType: "json",
					success(res) {
						that.currencyName = res.data.assetsname;
						that.yqtext = res.data.yqtext;
					},
					fail(error) {
						
					}
				})
			},
			back() {
				uni.navigateBack({
					delta: 1
				});
			},
			onadRewardedLoad() {
				console.log('激励视频广告数据加载成功');
			},
			onaderror(e) {
				var that = this;
				// 广告加载失败
				uni.showToast({
					title: that.$t('user.rebate.adloadfail'),
					icon: "none"
				});
			},
			onadRewardedClose(e) {
				var that = this;
				const detail = e.detail;
				// 用户点击了【关闭广告】按钮
				if (detail && detail.isEnded) {
					// 正常播放结束
					uni.showToast({
						title: that.$t('user.rebate.playcomplet'),
						icon: "none"
					});
				} else {
					uni.showToast({
						title: that.$t('user.rebate.unadvertplayback'),
						icon: "none"
					});
				}
			},
			showModal(e) {
				this.modalName = e.currentTarget.dataset.target
			},
			hideModal(e) {
				this.modalName = null
			},
			toLink(text) {
				var that = this;
				if (!localStorage.getItem('token') || localStorage.getItem('token') == "") {
					uni.showToast({
						title: that.$t('common.plslogin'),
						icon: 'none'
					})
					return false;
				}
				uni.navigateTo({
					url: text
				});
			},
			userrecharge() {
				var that = this;
				uni.navigateTo({
					url: '/pages/user/userrecharge'
				});
			},
			formatDate(datetime) {
				var datetime = new Date(parseInt(datetime * 1000));
				// 获取年月日时分秒值  slice(-2)过滤掉大于10日期前面的0
				var year = datetime.getFullYear(),
					month = ("0" + (datetime.getMonth() + 1)).slice(-2),
					date = ("0" + datetime.getDate()).slice(-2),
					hour = ("0" + datetime.getHours()).slice(-2),
					minute = ("0" + datetime.getMinutes()).slice(-2);
				//second = ("0" + date.getSeconds()).slice(-2);
				// 拼接
				var result = year + "-" + month + "-" + date + " " + hour + ":" + minute;
				// 返回
				return result;
			},
			tovipDiscount(num) {
				if (Number(num) <= 0) {
					return 0;
				} else {
					num = num.toString();
					num = num.replace("0.", "");
					return num;
				}
			},
			//激励视频
			createAd() {
				var that = this;
				var rewardedVideoAd = this.rewardedVideoAd = uni.createRewardedVideoAd(this.adOption);
				rewardedVideoAd.onLoad(() => {
					this.loading = false;
					this.loadError = false;
				});
				rewardedVideoAd.onClose((res) => {
					this.loading = true;
					// 用户点击了【关闭广告】按钮
					if (res && res.isEnded) {
						// 正常播放结束
						that.adsGiftNotify();
					} else {
						// 播放中途退出
						console.log("onClose " + res.isEnded);
						setTimeout(() => {
							uni.showToast({
								title: that.$t('user.rebate.unadvertplayback'),
								duration: 10000,
								position: 'bottom'
							})
						}, 500)
					}
					uni.hideLoading();
				});
				rewardedVideoAd.onError((err) => {
					uni.hideLoading();
					this.loading = false;
					if (err.code && ERROR_CODE.indexOf(err.code) !== -1) {
						this.loadError = true;
					}
					uni.showToast({
						title: err.errMsg,
						duration: 10000,
						position: 'bottom'
					})
				});
				this.loading = true;
			},
			show() {
				var that = this;
				uni.showLoading();
				that.$Net.request({
					url: that.$API.adsGift(),
					data: {
						"token": that.token,
						"appkey": that.$API.getAppKey()
					},
					header: {
						'Content-Type': 'application/x-www-form-urlencoded'
					},
					method: "get",
					dataType: 'json',
					success: function(res) {
						uni.hideLoading();
						if (res.data.code == 1) {
							that.adsLogid = res.data.data.logid;
							const rewardedVideoAd = that.rewardedVideoAd;
							rewardedVideoAd.show().catch(() => {
								rewardedVideoAd.load()
									.then(() => rewardedVideoAd.show())
									.catch(err => {
										uni.showToast({
											title: err.errMsg || err.message,
											duration: 5000,
											position: 'bottom'
										})
									})
							})
						} else {
							uni.showToast({
								title: res.data.msg,
								icon: 'none'
							})
						}
					},
					fail: function(res) {
						uni.showToast({
							title: that.$t('common.networkfail'),
							icon: 'none'
						})
					}
				})
			},
			adsGiftNotify() {
				var that = this;
				that.$Net.request({
					url: that.$API.adsGiftNotify(),
					data: {
						"token": that.token,
						"logid": that.adsLogid
					},
					header: {
						'Content-Type': 'application/x-www-form-urlencoded'
					},
					method: "get",
					dataType: 'json',
					success: function(res) {
						if (res.data.code == 1) {
							uni.showToast({
								title: that.$t('user.rebate.obtained') + res.data.data.award + that.currencyName + that.$t('user.rebate.reward'),
								duration: 3000,
								position: 'bottom'
							})
						}
					},
					fail: function(res) {
						uni.showToast({
							title: that.$t('common.networkfail'),
							icon: 'none'
						})
					}
				})
			},
			reloadAd() {
				this.loading = true;
				this.rewardedVideoAd.load();
			},
			copy(text) {
				var that = this;
				uni.setClipboardData({
					data: text,
					success: () => {
						uni.showToast({
							title: that.$t('common.copysuccess'),
							icon: 'success'
						})
					}
				});
				let textarea = document.createElement("textarea")
				textarea.value = text
				textarea.readOnly = "readOnly"
				document.body.appendChild(textarea)
				textarea.select() // 选中文本内容
				textarea.setSelectionRange(0, text.length)
				uni.showToast({ //提示
					title: that.$t('common.copysuccess'),
					icon: 'success'
				})
				result = document.execCommand("copy")
				textarea.remove()
			},
			getInvitationCode() {
				var that = this;
				var token = "";
				if (localStorage.getItem('userinfo')) {
					var userInfo = JSON.parse(localStorage.getItem('userinfo'));
					token = userInfo.token;
				}
				that.$Net.request({
					url: that.$API.getInvitationCode(),
					data: {
						"token": token
					},
					header: {
						'Content-Type': 'application/x-www-form-urlencoded'
					},
					method: "get",
					dataType: 'json',
					success: function(res) {
						var timer = setTimeout(function() {
							that.isLoading = 1;
							clearTimeout('timer')
						}, 300)
						if (res.data.code == 1) {
							that.invitationCode = res.data.data;
							var inviteJson = {
								"type": "Invite",
								"code": that.invitationCode
							}
							// that.codeImg = that.$API.qrCode() + "?codeContent=" + encodeURIComponent(JSON
							// 	.stringify(inviteJson));
						}else if(res.data.msg=="邀请码功能已关闭"){
							that.islock = true;
						}
					},
					fail: function(res) {
						var timer = setTimeout(function() {
							that.isLoading = 1;
							clearTimeout('timer')
						}, 300)
						uni.showToast({
							title: that.$t('common.networkfail'),
							icon: 'none'
						})
					}
				})
			},
			dtImg() {
				var that = this;
				var url = that.codeImg;
				// #ifdef APP-PLUS
				uni.downloadFile({
					url: url,
					success: (res) => {
						if (res.statusCode === 200) {
							uni.saveImageToPhotosAlbum({
								filePath: res.tempFilePath,
								success: function() {
									if (that.payType == 1) {
										uni.showToast({
											title: that.$t('user.rebate.imagesaved'),
											icon: "none"
										});
									} else {
										uni.showToast({
											title: that.$t('user.rebate.savesuccess'),
											icon: "none"
										});
									}
								},
								fail: function() {
									uni.showToast({
										title: that.$t('user.rebate.savefailreset'),
										icon: "none"
									});
								}
							});
						}
					}
				})
				// #endif
				// #ifdef H5
				uni.showToast({
					title: that.$t('user.rebate.pressqrcode'),
					icon: "none"
				});
				// #endif
			},
		},
		components: {
			waves
		}
	}
</script>

<style>
.menu-item {
	padding: 20rpx 30rpx;
	display: flex;
	justify-content: space-between;
	align-items: center;
}

.invite {
	padding: 30rpx;
}

.invite-title {
	text-align: center;
}

.text-price::before {
	content: "邀请码:";
	font-size: 28rpx;
	color: #666;
	margin-right: 10rpx;
}

.text-content {
	font-size: 28rpx;
	color: #666;
	line-height: 1.8;
}

.cu-btn.round {
	border-radius: 50rpx;
	padding: 0 40rpx;
}

.bg-gradual-orange {
	background-image: linear-gradient(45deg, #ff9700, #ed1c24);
	color: #ffffff;
}

.bg-gradual-blue {
	background-image: linear-gradient(45deg, #0081ff, #1cbbb4);
	color: #ffffff;
}
</style>